<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加文章</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert
        title="发布文章工作区"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>
      <el-steps
        space="33.33%"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="正文撰写"></el-step>
        <el-step title="完善信息"></el-step>
        <el-step title="发布"></el-step>
      </el-steps>
      <!-- tab栏区 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs v-model="activeIndex" :tab-position="'left'">
          <el-tab-pane label="正文撰写" name="0"> </el-tab-pane>
          <el-tab-pane label="完善信息" name="1">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="addForm.title"></el-input>
            </el-form-item>
            <el-form-item label="文章简介" prop="introduction">
              <el-input v-model="addForm.introduction"></el-input>
            </el-form-item>
            <el-form-item label="首图地址" prop="firstPicture">
              <el-input v-model="addForm.firstPicture"></el-input>
            </el-form-item>
            <el-form-item label="文章分类" prop="">
              <el-select v-model="addForm.typeId" placeholder="请选择">
                <el-option
                  v-for="item in cateList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文章标签">
              <el-select
                v-model="selectedTagIds"
                multiple
                placeholder="请选择"
                size="medium"
                class="my-el-select"
              >
                <el-option
                  v-for="item in tagList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <br />
              <el-tag v-for="(item, i) in newTags" :key="i" closable>{{
                item
              }}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput"
                >+ New Tag</el-button
              >
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="发布" name="2">
            <el-button type="primary" @click="publishBlog"
              >发布<i class="el-icon-upload el-icon--right"></i
            ></el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import $ from "jquery";
export default {
  data() {
    return {
      activeIndex: 0,
      addForm: {
        title: "",
        introduction: "",
        firstPicture: "",
        views: 0,
        typeId: "",
        tagIds: [],
        content: "",
      },
      addFormRules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        introduction: [{ required: true, message: "请输入文章简介", trigger: "blur" }],
        firstPicture: [
          { required: true, message: "请输入文章首图地址", trigger: "blur" },
        ],
      },
      cateList: [],
      tagList: [],
      selectedTagIds: [],
      //selectedCateId: "",
      //最终生成的编辑器
      editor: null,
      inputVisible: false,
      //标签文本框输入的值
      inputValue: "",
      //标签文本
      newTags: [],
      //默认选项
      defaultOptions: {
        width: "100%",
        height: 600,
        path: "/lib/editormd/lib/",
        theme: "dark",
        previewTheme: "dark",
        editorTheme: "pastel-on-dark",
        //markdown : md,   //动态设置的markdown文本
        codeFold: true,
        //syncScrolling : false,
        saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
        searchReplace: true,
        //watch : false,                // 关闭实时预览
        htmlDecode: "style,script,iframe|on*", // 开启 HTML 标签解析，为了安全性，默认不开启
        //toolbar  : false,             //关闭工具栏
        //previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
        emoji: true,
        taskList: true,
        tocm: true, // Using [TOCM]
        tex: true, // 开启科学公式TeX语言支持，默认关闭
        flowChart: true, // 开启流程图支持，默认关闭
        sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
        //dialogLockScreen : false,   // 设置弹出层对话框不锁屏，全局通用，默认为true
        //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
        //dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为true
        //dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为0.1
        //dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
        // imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        // imageUploadURL: "./php/upload.php",
        onload: function () {
          //   console.log('onload', this);
          //   this.fullscreen();
          //   this.unwatch();
          //   this.watch().fullscreen();
          //   this.setMarkdown("#PHP");
          //   this.width("100%");
          //   this.height(480);
          //  this.resize("100%", 640);
        },
      },
    };
  },
  props: {
    /**
     * editormd挂载元素的id
     */
    id: {
      type: String,
      default: "pane-0",
    },
    /**
     * editormd的选项对象
     */
    options: {
      type: Object,
    },
  },
  created() {
    this.getCateList();
    this.getTagList();
  },
  mounted() {
    let vm = this;
    this.requireEditor(function () {
      vm.editor = editormd(vm.id, vm.getOptions());
    });
  },
  methods: {
    requireEditor(callback) {
      let vm = this;
      //设置全局变量，因为editormd依赖jquery
      window.$ = window.jQuery = $;
      //异步加载并执行
      $.getScript("/lib/editormd/editormd.min.js", function (script) {
        callback();
      });
      //加载css
      $("head").append(
        $('<link rel="stylesheet" type="text/css" />').attr(
          "href",
          "/lib/editormd/css/editormd.min.css"
        )
      );
    },
    /**
     * 得到最终的options，组件属性上获得的选项覆盖此处的默认选项
     */
    getOptions() {
      return Object.assign(this.defaultOptions, this.options);
    },
    // 获取所有分类
    async getCateList() {
      const { data: res } = await this.$http.get("type");
      this.cateList = res.data;
    },
    // 获取所有标签
    async getTagList() {
      const { data: res } = await this.$http.get("tag");
      this.tagList = res.data;
    },
    // 添加标签
    handleInputConfirm() {
      if (this.inputValue.trim().length === 0) {
        this.inputValue = "";
        this.inputVisible = false;
        return;
      }
      this.newTags.push(this.inputValue.trim());
      // this.addForm.newTags.push(this.inputValue.trim());
      this.inputValue = "";
      this.inputVisible = false;
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async publishBlog() {
      this.addForm.content = this.editor.getMarkdown();
      this.addForm.tagIds = this.selectedTagIds;
      // 判断有无新增标签
      if (this.newTags.length !== 0) {
        // 先调用新增标签接口
        const { data: res } = await this.$http.post("insertTags", this.newTags);
        // 取标签id
        let newAddTagIds = [];
        res.data.generatedMaps.map((v) => newAddTagIds.push(v.id));
        this.addForm.tagIds.push(...newAddTagIds);
      }
      //console.log(this.addForm);
      const { data: res } = await this.$http.post("blog", this.addForm);
      if (res.meta.status === 0) {
        this.$message.success("发布文章成功！");
      }
    },
  },
};
</script>

<style lang="less">
#pane-1 {
  z-index: 999 !important;
}
.input-new-tag {
  width: 120px !important;
}
.el-tag {
  margin-right: 10px;
}
.editormd-theme-dark {
  border: none !important;
}
.my-el-select {
  width: 400px !important;
  margin-bottom: 20px;
}
</style>